package com.senven.books.framework.web.service;

import com.senven.books.framework.web.model.LoginUser;
import com.senven.books.modules.system.role.service.SysRoleService;
import com.senven.books.modules.system.user.entity.SysUser;
import com.senven.books.modules.system.user.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author : longshengyi
 * @description :
 * @createDate : 2024/7/21 11:43
 */
@Service
public class CustomUserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService sysUserServiceImpl;

    @Autowired
    private SysRoleService sysRoleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysuser = sysUserServiceImpl.getSysUserByUsername(username);
        if(Objects.isNull(sysuser)){//判断user对象是否为空。当在数据库没有查到数据时，user就会为空，也就会进入这个判断
            throw new RuntimeException("用户名或者密码错误");
        }
        List<String> list = sysRoleService.findRoleByUserId(sysuser.getId());
        return new LoginUser(sysuser,list);
    }
}
